 
layui.define(['table','form'], function(exports){
    var $ = layui.$
    ,form = layui.form
    ,table = layui.table
    ,setter = layui.setter
    ,admin = layui.admin
    ,dropdown = layui.dropdown;
    var renderTable;
    var field = '';
    var colsArr ;

    var tableTitle;
    var tableField; //表头字段
    var tableSearch = [];//全局搜索条件
    var tableHead;//表头字段


      

    
    // var currentMenuId = "5e68cc3e00ae426da7a7e8fcd07b1389";
    //
    // admin.req({
    //     url: setter.host+'/adminmanager/menu/menuListHead'
    //     ,type:'post'
    //     ,contentType: "application/json; charset=utf-8"
    //     ,data:'{menuId:"'+currentMenuId+'"}'
    //     ,done: function(res){
    //       //请求成功后
    //       if(res.status == setter.response.statusCode.status_Success){
    //         field = res.data;
    //
    //
    //       }else{
    //     	  window.location.href = setter.host+'/error/toNoPower?msg='+res.msg;
    //       }
    //     }
    // });

    tableRender();
      
    function tableRender(){
        colsArr = [
            {field: '', title: '序号',width: 40,type: 'numbers'},
            {field: 'reservationNumber', title: '单号',align:'center'},
            {field: 'actualArrivalTime', title: '到达时间',align:'center'},
            {field: 'actualPlatformNumber', title: '查看月台', align:'center',toolbar: "#checkPlatform"},
            {field: 'nowStatus', style:'color:red', title: '状态',align:'center',sort: true ,width:100,templet: function(d){
                    if(d.nowStatus ==0){return '发起预约'}
                    else if(d.nowStatus==1){return '等待确认'}
                    else if(d.nowStatus==2){return '预约已确认'}
                    else if(d.nowStatus==3){return '已发车'}
                    else if(d.nowStatus==4){return '已到达'}
                    else if(d.nowStatus==5){return '开始装卸'}
                    else if(d.nowStatus==6){return '装卸完毕'}
                    else if(d.nowStatus==7){return '预约已完成'}
                    else if(d.nowStatus==8){return '预约异常'}
                    else if(d.nowStatus==9){return '预约取消'}
                }
            },
            {field: 'orderNumber', title: '订单号', align:'center'},
            {field: 'driverNumber', title: '查看司机',align:'center',toolbar: "#checkDriver"},
            {field: 'timeoutStatus', title: '超时状态',align:'center',templet: function(d){
                    if(d.nowStatus ==0){return '准时'}
                    else if(d.nowStatus==1){return '迟到'}
                    else if(d.nowStatus==2){return '早到'}
                }},
            {field: 'receiverNumber', title: '查看收货员',align:'center',toolbar: "#checkReceiver"},
            {fixed: 'right',title: '审批预约',align: 'center' ,toolbar:'#checkReservation'}
        ]





        layui.each(colsArr,function(inx,val){
            console.log(val)
            field += val.hasOwnProperty('field')?val.field:'';
            field += ',';

            tableHead += val.hasOwnProperty('field')?val.field:'';
            tableHead += ',';

            tableTitle += val.hasOwnProperty('title')?(val.hide?'':val.title+','):',';

            tableField += val.hasOwnProperty('field')?(val.hide?'':val.field+','):',';
        })

        field = field.substring(field.indexOf(',')+1,field.length-2);
        loadTable(colsArr);
    }



    function loadTable(){
        var tableWhere = {};
        tableWhere.headField = field;

        table.render({
            elem: '#LAY-reservation-list',
            limit: 15,
            limits:[15,30,50],
            cols: [colsArr],
            height: 'full-15',
            page: true, //开启分页
            toolbar: 'default',
            method:'get',
            url: '/unite_platform/reservation/receiveManager/getAllReservation'
            ,text: {
                none: '暂无相关数据'
            }
        });

        //监听行工具事件
        table.on('tool(LAY-reservation-list)', function(obj){
            //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                ,layEvent = obj.event; //获得 lay-event 对应的值


            console.log(obj)
            layer.open({
                type: 1
                ,title: '工作记录'
                ,content: '<div class="layui-container" style="width: 98%"><table id="LAY-human-gzjl" lay-filter="LAY-human-gzjl" class=""></table></div>'
                ,shadeClose: true//开启遮罩关闭
                ,area: ['70%', '90%']
                ,maxmin: true
                ,btn: ['确定']
                ,success: function(layero, index){
                    //     var body=layer.getChildFrame('body',index);//少了这个是不能从父页面向子页面传值的
                    //     //获取子页面的元素，进行数据渲染
                    // console.log(body)
                    //     body.contents().find("#user_id").val(data.id);


                    table.render({
                        elem: '#LAY-human-gzjl'  // 弹出层表格id
                        ,url: setter.host + '/human/menu/getGongzuo' // 后端请求URL地址
                        ,method: 'post'
                        ,where: {'headField':'gz_start,gz_over,gz_bumen,gz_gangwei','user_id':data.id}
                        ,page: true
                        ,contentType:"application/json; charset=utf-8"
                        ,cols: [[
                            {field: 'gz_start', title: '开始日期',sort:true,align:'center'},
                            {field: 'gz_over', title: '结束日期',sort:true,align:'center'},
                            {field: 'gz_bumen', title: '部门',sort:true,align:'center',width: 100, sort: true,},
                            {field: 'gz_gangwei', title: '岗位',align:'center',sort:true,sort: true,width: 130,},
                        ]]
                    })
                    }
                ,yes: function(index, layero){
                    layer.close(index)
                }
            });
        });
    }

    $('.layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });



    var active = {
        batchdel: function(){
            var checkData = renderTable.checkStatus()
                if(checkData.length === 0){
                    return layer.msg('请选择数据');
                }
            layer.prompt({
                formType: 1
                ,title: '敏感操作，请验证当前用户口令'
            }, function(value, index_prompt){
                var command = layui.sessionData('layuiSession').command;
                if(value == command){
                    layer.close(index_prompt);
                    layer.confirm('确定删除吗？', function(index_confirm) {
                        layer.close(index_confirm);
                        //因为是单选项，只能选择一个
                        if(checkData[0].hasOwnProperty('children')){
                            layer.confirm('该选择的删除数据有子菜单,确定都删除吗?', {icon: 3, title:'提示'}, function(index_del){
                                layer.close(index_del);
                                del(checkData[0].menuId,checkData[0].pId);
                            });
                        }else{
                            del(checkData[0].menuId,checkData[0].pId);
                        }
                    });
                }else{
                    layer.msg('口令错误');
                }
            });
        }
        ,add: function(){
            // layer.open({
            //     type: 2
            //     ,title: '添加菜单'
            //     ,content: setter.host+'/human/menu/toInsert'
            //     ,area: ['720px', '590px']
            //     ,btn: ['确定', '取消']
            //     ,yes: function(index, layero){
            //         var iframeWindow = window['layui-layer-iframe'+ index]
            //         ,submitID = 'LAY-menu-add-submit'
            //         ,submit = layero.find('iframe').contents().find('#'+ submitID);
            //         //监听提交
            //         iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
            //             var indexLoad = layer.msg('添加菜单，请稍后', {
            //                 icon: 16
            //                 ,shade: 0.01
            //             });
            //             admin.req({
            //             url: setter.host+'/human/menu/insert'
            //             ,type:'post'
            //             ,dataType:'json'
            //             ,contentType: "application/json; charset=utf-8"
            //             ,data:JSON.stringify(data.field)
            //             ,done: function(res){
            //                 //请求成功后
            //                 if(res.status == setter.response.statusCode.status_Success){
            //                     if(data.field.menuId == '-1'){
            //                         loadTable(colsArr,field);
            //                         }else{
            //                             renderTable.refresh(data.field.menuId);
            //                     }
            //                 }
            //                 layer.close(index);
            //                 layer.close(indexLoad);
            //                 layer.msg(res.msg);
            //             }
            //             });
            //         });
            //         submit.trigger('click');
            //     }
            // });
            var obj = {};
            obj.bakUrl = setter.host+'/human/menu/toMenuList';
            obj.jsType = 'add';
            layui.common.postUrl(obj,setter.host+'/human/menu/toInsert');
        }
        ,edit: function(){
            var checkData = renderTable.checkStatus();
            if(checkData.length > 1){
                return layer.msg('只能选中编辑一行');
            }
            if(checkData.length ===0 ){
                return layer.msg('请选择一行数据进行编辑');
            }
            layer.open({
                type: 2
                ,title: '编辑菜单'
                ,content: setter.host+'/human/menu/toEdit'
                ,area: ['720px', '590px']
                ,btn: ['确定', '取消']
                ,success:function(editFrame,index){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                    ,subBody = editFrame.find('iframe').contents();
                    //subBody.find('select[name=type]').find("option[value='button']").attr("selected",true);
                    var type = checkData[0].type;
                    // checkData.forEach((e)=>{
                    //     delete e.LAY_CHECKED;
                    //     delete e.LAY_INDETERMINATE;
                    //     delete e.LAY_INDEX;
                    //     delete e.isIndeterminate
                    //
                    //     for(let d in e){
                    //
                    //         switch (d){
                    //             case "id":
                    //
                    //                 break
                    //             case "name":
                    //
                    //                 subBody.find("input[name = name]").html(d[e])
                    //                 break
                    //             case "sex":
                    //                 // subBody.find("#sex").val(d[e])
                    //                 break
                    //             case "phone":
                    //                 subBody.find("#phone").val(d[e])
                    //                 break
                    //             case "entry_time":
                    //                 // subBody.find("#phone").val(d[e])
                    //                 break
                    //             case "work_age":
                    //                 // subBody.find("#work_age").html(d[e])
                    //                 break
                    //             case "post":
                    //                 // subBody.find("#post").val(d[e])
                    //                 break
                    //             case "stat":
                    //                 // subBody.find("#stat").val(d[e])
                    //                 break
                    //             case "nationality":
                    //                 subBody.find("#nationality").val(d[e])
                    //                 break
                    //             case "nation":
                    //                 // subBody.find("#nation").val(d[e])
                    //                 break
                    //             case "politics":
                    //                 // subBody.find("#politics").val(d[e])
                    //                 break
                    //             case "education":
                    //                 subBody.find("#education").val(d[e])
                    //                 break
                    //             case "school":
                    //                 subBody.find("#school").val(d[e])
                    //                 break
                    //             case "code":
                    //                 subBody.find("#code").val(d[e])
                    //                 break
                    //             case "birth":
                    //                 // subBody.find("#birth").val(d[e])
                    //                 break
                    //             case "registered":
                    //                 subBody.find("#registered").val(d[e])
                    //                 break
                    //             case "address":
                    //                 subBody.find("#address").val(d[e])
                    //                 break
                    //             case "number":
                    //                 subBody.find("#number").html(d[e])
                    //                 break
                    //             case "expire":
                    //                 // subBody.find("#expire").val(d[e])
                    //                 break
                    //             case "remarks":
                    //                 subBody.find("#remarks").val(d[e])
                    //                 break
                    //
                    //             default :
                    //                 break
                    //
                    //         }
                    //         // subBody.find(`"#${e}"`).val(e[d])
                    //     }
                    //
                    // })
                    // console.log(checkData[0])
                    subBody.find("#id").val(checkData[0].id)


                }
                ,yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                    ,submitID = 'LAY-menu-edit-submit'
                    ,submit = layero.find('iframe').contents().find('#'+ submitID);
                    //监听提交

                    console.log(iframeWindow,submitID,submit)
                    iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                        console.log(JSON.stringify(data.field))
//                        data.field.menuId = checkData[0].menuId;
//                        data.field.pId = checkData[0].pId;
                        admin.req({
                            url: setter.host+'/human/menu/upUser'
                            ,type:'post'
                            ,dataType:'json'
                            ,contentType: "application/json; charset=utf-8"
                            ,data:JSON.stringify(data.field)
                            ,done: function(res){
                            //请求成功后
                            if(res.status == setter.response.statusCode.status_Success){
                                if(data.field.pId == '-1'||data.field.toChangePid=='-1'){
                                    loadTable(colsArr,field);
                                }else{
                                    renderTable.refresh(data.field.pId);
                                    //如果更新的菜单与当前修改的父菜单不一样，那么还需要刷新新修改后的菜单
                                    if(data.field.toChangePid !='' && data.field.pId != data.field.toChangePid){
                                    	renderTable.refresh(data.field.toChangePid);
                                    }
                                }
                            }
                            layer.close(index);
                            layer.msg(res.msg);
                            }
                        });
                    });
                    submit.trigger('click');
                }
            });
        }
    }
    function del(menuId,pId){
        var indexLoad = layer.msg('删除菜单，请稍后', {
            icon: 16
            ,shade: 0.01
        });
        admin.req({
            url: setter.host+'/adminmanager/menu/batchdelMenu'
            ,type:'post'
            ,contentType: "application/json; charset=utf-8"
            ,data:'{"menuId":"'+menuId+'","pId":"'+pId+'"}'
            ,done: function(res){
                //请求成功后
                if(res.status == setter.response.statusCode.status_Success){
                        if(pId == '-1'){
                            loadTable(colsArr,field);
                        }else{
                            renderTable.refresh(pId);
                        }
                }
                layer.close(indexLoad);
                layer.msg(res.msg);
            }
        });
    }
    form.on('submit(LAY-human-normal-search)', function(data){
        var search = {};

        search.conditionField = data.field.whereKey;
        search.conditionValue = data.field.whereValue;
        search.conditionOption = 'like';
        tableSearch[0] = search;

//		tableSearch[data.field.whereKey] = data.field.whereValue;
        //执行重载
        // console.log(tableHead)
        // console.log(field)
        renderTable.reload({

            where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                search: tableSearch //查询字段
                ,headField:field //表头字段
                ,page:1//页码取第一页
            }
        });
    });
    //对外暴露的接口
      exports('select', {});
  });